import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WorksTagService } from '../works-tag/works-tag.service';
import { CreateWorkDto, WorksRo } from './dto/create-work.dto';
import { UpdateWorkDto } from './dto/update-work.dto';
import { WorksEntity } from './entities/work.entity';

@Injectable()
export class WorksService {

  constructor(
    @InjectRepository(WorksEntity)
    private readonly worksRepository: Repository<WorksEntity>,
    private readonly worksTagService: WorksTagService
  ) { }

  async create(createWorkDto) {
    const { name } = createWorkDto;
    if (!name) {
      throw new HttpException('缺少项目名称', HttpStatus.BAD_REQUEST);
    }
    const doc = await this.worksRepository.findOne({ where: { name } });
    if (doc) {
      throw new HttpException('项目名称已存在', HttpStatus.BAD_REQUEST);
    }
    let { tag } = createWorkDto;
    const tags = await this.worksTagService.findByIds(('' + tag).split(','));
    const worksParam: Partial<WorksEntity> = {
      ...createWorkDto,
      worksTags: tags,
    };

    const newWorks: WorksEntity = await this.worksRepository.create({
      ...worksParam,
    });
    const created = await this.worksRepository.save(newWorks);
    return created.id;
  }

  async findAll(query): Promise<WorksRo> {
    const { pageNum = 1, pageSize = 10, ...params } = query;
    const result = await this.worksRepository.findAndCount({
      // where:{category:query.category},
      where: query.status ? { status: query.status } : 'true',
      relations: ["worksTags"],
      order: {
        id: 'DESC',
      },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });
    const list = result[0].map((item) => item.toResponseObject());
    return { list, count: result[1] };
  }

  async findOne(id: number): Promise<any> {
    const qb = this.worksRepository
      .createQueryBuilder('works')
      .leftJoinAndSelect('works.worksTags', 'worksTag')
      .where('works.id=:id')
      .setParameter('id', id);

    const result = await qb.getOne();
    if (!result)
      throw new HttpException(`id为${id}的项目不存在`, HttpStatus.BAD_REQUEST);
    return result.toResponseObject()
  }

  async update(works) {
    //判断以下数据库中有没有传入的id对应的数据
    const existWorks = await this.worksRepository.findOne(works.id);
    if (!existWorks) {
      throw new HttpException(`id为${works.id}的项目不存在`, HttpStatus.BAD_REQUEST);
    }

    let { tag } = works;
    const tags = await this.worksTagService.findByIds(('' + tag).split(','));
    const worksParam: Partial<WorksEntity> = {
      ...works,
      worksTags: tags,
    };
    const updatePost = this.worksRepository.merge(existWorks, worksParam);
    return (await this.worksRepository.save(updatePost)).id;
  }
 
  async remove(id: number) {
    const existWorks = await this.worksRepository.findOne(id);
    if (!existWorks) {
      throw new HttpException(`id为${id}的项目不存在`, HttpStatus.BAD_REQUEST);
    }
    return await this.worksRepository.remove(existWorks);
  }
}
